
package com.eworking.eim.group;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smackx.Form;
import org.jivesoftware.smackx.FormField;
import org.jivesoftware.smackx.muc.Affiliate;
import org.jivesoftware.smackx.muc.HostedRoom;
import org.jivesoftware.smackx.muc.InvitationListener;
import org.jivesoftware.smackx.muc.MultiUserChat;
import org.jivesoftware.smackx.muc.Occupant;
import org.jivesoftware.smackx.muc.RoomInfo;

import android.content.Context;

import com.eworking.eim.EIMChatManager;
import com.eworking.eim.EIMConfig;
import com.eworking.eim.EIMConstants;
import com.eworking.eim.exception.EIMPermissionException;
import com.eworking.eim.receive.EIMMUCPresenceListener;
import com.eworking.eim.user.EIMAccountUtils;
import com.eworking.eim.util.EIMLog;
import com.eworking.eim.xmpp.XMPPConnectionManager;

public class EIMGroupManager {
    
    /** 日志输出标记 */
    private static final String _TAG = EIMGroupManager.class.getSimpleName();
    
    private static EIMGroupManager groupManager = null;
    
    protected Context context = null;
    
    /** XMPP服务器连接管理 */
    private XMPPConnectionManager xmppConnectionManager = null;
    
    /** 所有群组集合 */
    public Map<String, EIMGroup> allGroups = null;
    
    /** 所有群组聊天室集合 */
    private Map<String, MultiUserChat> allMultiUserChats = new HashMap<String, MultiUserChat>();
    
    /** 群组操作监听器集合 */
    public List<EIMGroupChangeListener> allGroupChangeListeners = new ArrayList<EIMGroupChangeListener>();
    
    /** 所有群组操作事件集合 */
    public List<EIMGroupChangeEvent> allGroupChangeEvents = new ArrayList<EIMGroupChangeEvent>();
    
    /** 当前登陆用户账号 */
    private String currentAccount;
    
    /** 当前登陆用户企业账号 */
    private String currentJID;
    
    /** 是否自动接受邀请 */
    public boolean autoAcceptInvitation = true;
    
    private InvitationListener invitationListener = null;
    
    public static EIMGroupManager getInstance() {
        if (groupManager == null) {
            groupManager = new EIMGroupManager();
        }
        return groupManager;
    }
    
    public void init(Context context, XMPPConnectionManager xmppConnectionManager) {
        try {
            this.context = context;
            this.xmppConnectionManager = xmppConnectionManager;
            this.currentAccount = EIMChatManager.getInstance().getCurrentAccount();
            this.currentJID = EIMAccountUtils.getJIDFromAccount(currentAccount);
            
            this.invitationListener = new EIMInvitationListener();
            MultiUserChat.addInvitationListener(xmppConnectionManager.getConnection(), this.invitationListener);
            this.allMultiUserChats.clear();
            
            PacketTypeFilter packetTypeFilter = new PacketTypeFilter(Presence.class);
            this.xmppConnectionManager.getConnection()
                .addPacketListener(new EIMMUCPresenceListener(), packetTypeFilter);
        } catch (Exception e) {
            return;
        }
        
    }
    
    /**
     * 创建私有群组
     * 
     * @param groupName 群组名称
     * @param groupDesc 群组描述
     * @param members 群组成员
     */
    public EIMGroup createPrivateGroup(String groupName, String groupDesc, String[] members) {
        return this.createPrivateGroup(groupName, groupDesc, members, false);
    }
    
    /**
     * 创建私有群组
     * 
     * @param groupName 群组名称
     * @param groupDesc 群组描述
     * @param members 群组成员
     * @param isAllowInvites 是否允许邀请
     */
    public EIMGroup createPrivateGroup(String groupName, String groupDesc, String[] members, boolean isAllowInvites) {
        try {
            // 生成群组ID
            String groupId = this.generateGroupId();
            String groupJID = EIMAccountUtils.getGroupJIDFromGroupId(groupId);
            // 在XMPP服务器创建群组
            this.createPrivateGroupToXMPP(groupJID, groupName, groupDesc, currentAccount, isAllowInvites);
            
            List<String> lstMembers = new ArrayList<String>();
            // 添加群组成员
            for (String member : members) {
                String memberJID = EIMAccountUtils.getJIDFromAccount(member);
                this.addMemberToMUC(groupJID, memberJID, true);
                lstMembers.add(member);
            }
            
            EIMGroup group = new EIMGroup(groupId);
            group.setGroupName(groupName);
            group.setDescription(groupDesc);
            group.setOwner(currentAccount);
            lstMembers.add(currentAccount);
            // 保存群组到数据库中
            EIMGroupTable.getInstance().insertGroup(group);
            // 放入缓存
            this.allGroups.put(groupId, group);
            return group;
        } catch (Exception e) {
            EIMLog.e(_TAG, "创建私有群组失败：" + e.getMessage());
        }
        return null;
    }
    
    /**
     * 在XMPP服务器创建群组
     * 
     * @param groupJID 群组企业账号
     * @param groupName 群组名称
     * @param groupDesc 群组描述
     * @param currentAccount 当前登陆账号
     * @param isAllowInvites
     */
    private void createPrivateGroupToXMPP(String groupJID, String groupName, String groupDesc, String currentAccount,
        boolean isAllowInvites) {
        try {
            // 创建群组
            MultiUserChat multiUserChat = new MultiUserChat(this.xmppConnectionManager.getConnection(), groupJID);
            multiUserChat.create(currentAccount);
            
            Form form = multiUserChat.getConfigurationForm();
            Form answerForm = form.createAnswerForm();
            Iterator<FormField> iterFormFields = answerForm.getFields();
            while (iterFormFields.hasNext()) {
                FormField formField = iterFormFields.next();
                if ((!(FormField.TYPE_HIDDEN.equals(formField.getType()))) && (formField.getVariable() != null)) {
                    answerForm.setDefaultAnswer(formField.getVariable());
                }
                // 群组属性设置
                answerForm.setAnswer("muc#roomconfig_persistentroom", true);
                answerForm.setAnswer("muc#roomconfig_membersonly", true);
                answerForm.setAnswer("muc#roomconfig_moderatedroom", true);
                answerForm.setAnswer("muc#roomconfig_publicroom", false);
                answerForm.setAnswer("members_by_default", true);
                answerForm.setAnswer("muc#roomconfig_allowinvites", isAllowInvites);
                answerForm.setAnswer("muc#roomconfig_roomname", groupName);
                answerForm.setAnswer("muc#roomconfig_roomdesc", groupDesc);
                multiUserChat.sendConfigurationForm(answerForm);
                // 加入群组
                multiUserChat.join(currentAccount);
                // 放入缓存
                this.addMUC(groupJID, multiUserChat);
            }
        } catch (Exception e) {
            EIMLog.e(_TAG, "创建私有群组失败：" + e.getMessage());
        }
    }
    
    /**
     * 添加人员到群组中
     * 
     * @param groupId
     * @param members
     */
    public void addMembersToGroup(String groupId, String[] members) {
        try {
            EIMGroup group = this.allGroups.get(groupId);
            if (group == null) {
                EIMLog.d(_TAG, "该群组不存在：" + groupId);
                return;
            }
            // 检查是否为群组
            this.checkGroupOwner(group, EIMConstants._PERMISSION_ERROR_ADD);
            String groupJID = EIMAccountUtils.getGroupJIDFromGroupId(groupId);
            
            for (String member : members) {
                // 添加到XMPP服务器
                String memberJID = EIMAccountUtils.getJIDFromAccount(member);
                this.addMemberToMUC(groupJID, memberJID, true);
                group.addMember(member);
            }
            // 保存到数据库中
            EIMGroupTable.getInstance().insertGroup(group);
        } catch (Exception e) {
            EIMLog.e(_TAG, "添加群组成员失败：" + e.getMessage());
        }
    }
    
    public void removeMemberFromGroup(String groupId, String member) {
        try {
            EIMGroup group = this.allGroups.get(groupId);
            if (group == null) {
                EIMLog.d(_TAG, "该群组不存在：" + groupId);
                return;
            }
            // 检查是否为群组
            this.checkGroupOwner(group, EIMConstants._PERMISSION_ERROR_ADD);
            String groupJID = EIMAccountUtils.getGroupJIDFromGroupId(groupId);
            String memberJID = EIMAccountUtils.getJIDFromAccount(member);
            // 从XMPP服务器中删除
            this.removeMemberFromMUC(groupJID, memberJID);
            group.removeMember(member);
            // 更新数据库
            EIMGroupTable.getInstance().updateGroup(group);
        } catch (Exception e) {
            EIMLog.e(_TAG, "删除群组成员失败：" + e.getMessage());
        }
    }
    
    /**
     * 从XMPP服务端获取群组信息
     * 
     * @param groupId
     * @return
     */
    public EIMGroup getGroupFromServer(String groupId) {
        EIMGroup group = null;
        try {
            String groupJID = EIMAccountUtils.getGroupJIDFromGroupId(groupId);
            group = getMUC(groupJID, currentAccount, true, false);
            if (group == null) {
                EIMLog.e(_TAG, "从XMPP服务端获取群组信息失败");
            }
        } catch (Exception e) {
            EIMLog.e(_TAG, "从XMPP服务端获取群组信息失败：" + groupId + e.getMessage());
        }
        return group;
    }
    
    /**
     * 从XMPP服务端获取群组列表
     * 
     * @return
     */
    public synchronized List<EIMGroup> getGroupsFromServer() {
        List<EIMGroup> lstGroups = null;
        try {
            // 从服务端获取群组列表
            lstGroups = this.getGroupsFromServer(this.currentJID);
            // 更新客户端群组列表（数据库、缓存）
            this.syncGroupsWithRemoteGroupList(lstGroups);
        } catch (Exception e) {
            EIMLog.e(_TAG, "从XMPP服务端获取群组列表失败：" + e.getMessage());
        }
        return lstGroups;
    }
    
    /**
     * 从XMPP服务端获取群组列表
     * 
     * @param account 用户企业账号
     * @return
     */
    private List<EIMGroup> getGroupsFromServer(String JID) {
        List<EIMGroup> lstGroups = new ArrayList<EIMGroup>();
        try {
            // 从服务端获取所有房间列表
            Collection<HostedRoom> rooms =
                MultiUserChat.getHostedRooms(this.xmppConnectionManager.getConnection(), EIMConfig.MUC_DOMAIN);
            for (HostedRoom room : rooms) {
                EIMGroup group = getMUC(room.getJid(), JID, false, true);
                lstGroups.add(group);
            }
        } catch (Exception e) {
            EIMLog.e(_TAG, "从XMPP服务端获取群组列表失败：" + e.getMessage());
        }
        return lstGroups;
    }
    
    /**
     * 同步缓存中的群组信息
     * 
     * @param groups
     * @return
     */
    private void syncGroupsWithRemoteGroupList(List<EIMGroup> groups) {
        try {
            List<String> serverGroupIds = new ArrayList<String>();
            for (EIMGroup group : groups) {
                if (this.allGroups.containsKey(group.getGroupId())) {
                    EIMLog.d(_TAG, "缓存中存在该群组信息");
                } else {
                    // 更新数据库、缓存中的群组信息
                    this.createOrUpdateLocalGroup(group);
                }
                serverGroupIds.add(group.getGroupId());
            }
            // 避免死锁
            Set<String> groupIdsSet = new HashSet<String>();
            groupIdsSet.addAll(this.allGroups.keySet());
            
            Iterator<String> cacheGroupIds = groupIdsSet.iterator();
            while (cacheGroupIds.hasNext()) {
                String groupId = cacheGroupIds.next();
                // 服务端是否存在该群组，如果不存在，则删除
                if (!serverGroupIds.contains(groupId)) {
                    this.deleteGroupClient(groupId);
                }
            }
        } catch (Exception e) {
            EIMLog.e(_TAG, "同步缓存群组数据失败：" + e.getMessage());
        }
    }
    
    /**
     * 创建或更新群组信息
     * 
     * @param group
     */
    public void createOrUpdateLocalGroup(EIMGroup group) {
        // 从数据库中获取群组信息
        EIMGroup tempGroup = EIMGroupTable.getInstance().queryGroupByGroupName(group.getGroupId());
        if (tempGroup == null) {
            // 新增群组信息
            EIMGroupTable.getInstance().insertGroup(group);
        } else {
            // 修改群组信息
            EIMGroupTable.getInstance().updateGroup(group);
        }
        // 更新缓存中的群组信息
        this.allGroups.put(group.getGroupId(), group);
    }
    
    /**
     * 删除成员，从XMPP服务器中
     * 
     * @param groupJID
     * @param memberJID
     * @throws XMPPException
     */
    private void removeMemberFromMUC(String groupJID, String memberJID) throws XMPPException {
        MultiUserChat multiUserChat = getMUC(groupJID);
        multiUserChat.revokeMembership(memberJID);
        String memberAccount = EIMAccountUtils.getAccountFromJID(memberJID);
        try {
            multiUserChat.kickParticipant(memberAccount, "RemoveFromGroup");
        } catch (Exception localException) {
            localException.printStackTrace();
        }
    }
    
    /**
     * 添加群组成员
     * 
     * @param groupJID
     * @param memberJID
     * @param paramBoolean
     * @throws XMPPException
     */
    private void addMemberToMUC(String groupJID, String memberJID, boolean paramBoolean) throws XMPPException {
        MultiUserChat multiUserChat = getMUC(groupJID);
        if (paramBoolean) {
            multiUserChat.invite(memberJID, "私有群组");
        }
        multiUserChat.grantMembership(memberJID);
    }
    
    /**
     * 退出并删除群组
     * 
     * @param groupId
     */
    public void exitAndDeleteGroup(String groupId) {
        try {
            EIMGroup group = this.allGroups.get(groupId);
            // 检查当前登陆人是否为群组
            checkGroupOwner(group, EIMConstants._PERMISSION_ERROR_DELETE);
            String groupJID = EIMAccountUtils.getGroupJIDFromGroupId(groupId);
            this.deleteMUC(groupJID);
            if (group != null) {
                this.deleteGroupClient(groupId);
            }
        } catch (Exception e) {
            EIMLog.e(_TAG, "退出并删除群组失败：" + e.getMessage());
        }
    }
    
    /**
     * 退出群组
     * 
     * @param groupId 群组ID
     */
    public void exitFromGroup(String groupId) {
        try {
            String groupJID = EIMAccountUtils.getGroupJIDFromGroupId(groupId);
            // 退出群组，并移除成员
            this.leaveMUCRemoveMember(groupJID, this.currentJID);
            // 从本地缓存移除并删除会话
            this.deleteGroupClient(groupId);
        } catch (Exception e) {
            EIMLog.e(_TAG, "退出群组失败：" + e.getMessage());
        }
    }
    
    /**
     * 接受对方邀请，加入群组
     * 
     * @param groupId 群組ID
     */
    public void acceptInvitation(String groupId) {
        try {
            String groupJID = EIMAccountUtils.getGroupJIDFromGroupId(groupId);
            MultiUserChat multiUserChat = this.getMUC(groupJID);
            if (!multiUserChat.isJoined()) {
                multiUserChat.join(this.currentAccount);
            }
            // 从服务端获取群组信息
            EIMGroup group = this.getGroupFromServer(groupId);
            // 更新数据库、缓存
            this.createOrUpdateLocalGroup(group);
        } catch (Exception e) {
            EIMLog.e(_TAG, "接受对方邀请加入群组,groupId:" + groupId + " : " + e.getMessage());
        }
    }
    
    /**
     * 拒绝对方邀请加入群组
     * 
     * @param groupId 群组ID
     * @param reason 原因
     */
    public void declineInvitation(String groupId, String inviter, String reason) {
        try {
            String groupJID = EIMAccountUtils.getGroupJIDFromGroupId(groupId);
            String inviterJID = EIMAccountUtils.getJIDFromAccount(inviter);
            // 拒绝对方邀请
            MultiUserChat.decline(this.xmppConnectionManager.getConnection(), groupJID, inviterJID, reason);
            // 删除本地群组信息
            this.deleteGroupClient(groupId);
        } catch (Exception e) {
            EIMLog.e(_TAG, "拒绝对方邀请加入群组,groupId:" + groupId + " : " + e.getMessage());
        }
    }
    
    /**
     * 邀请人员加入群组
     * 
     * @param groupId 群组ID
     * @param members 成员集合
     * @param reason 原因
     */
    public void inviteMember(String groupId, String[] members, String reason) {
        try {
            List<String> lstMembers = new ArrayList<String>();
            for (String member : members) {
                String memberJID = EIMAccountUtils.getJIDFromAccount(member);
                lstMembers.add(memberJID);
            }
            this.inviteMemberMUC(groupId, lstMembers, reason);
        } catch (Exception e) {
            EIMLog.e(_TAG, "邀请成员加入群组失败,groupId:" + groupId + " : " + e.getMessage());
        }
    }
    
    /**
     * 邀请人员加入群组，更新到XMPP服务器
     * 
     * @param groupJID
     * @param members
     * @param reason
     */
    private void inviteMemberMUC(String groupId, List<String> members, String reason) {
        try {
            String groupJID = EIMAccountUtils.getGroupJIDFromGroupId(groupId);
            MultiUserChat multiUserChat = getMUC(groupJID);
            EIMGroup group = this.getGroup(groupId);
            if (members != null && members.size() > 0) {
                for (String memberJID : members) {
                    // 邀请成员加入群组
                    multiUserChat.invite(memberJID, reason);
                    if (group.isAllowInvites()) {
                        group.addMember(EIMAccountUtils.getAccountFromJID(memberJID));
                    }
                }
            }
        } catch (Exception e) {
            EIMLog.e(_TAG, "邀请成员加入群组失败,groupId:" + groupId + " : " + e.getMessage());
        }
    }
    
    /**
     * 退出群组并移除成员
     * 
     * @param groupJID
     * @param JID
     * @throws XMPPException
     */
    private void leaveMUCRemoveMember(String groupJID, String JID) throws XMPPException {
        MultiUserChat multiUserChat = getMUC(groupJID);
        // 退出群组
        multiUserChat.leave();
        try {
            // 群组中移除当前登陆人
            multiUserChat.revokeMembership(JID);
        } catch (Exception e) {
            EIMLog.e(_TAG, "退出群组失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除群组
     * 
     * @param groupJID
     * @throws XMPPException
     */
    private void deleteMUC(String groupJID) throws XMPPException {
        MultiUserChat multiUserChat = getMUC(groupJID);
        multiUserChat.destroy("delete-group", null);
    }
    
    /**
     * 检查是否为群主
     * 
     * @param group
     * @param error
     * @throws EIMPermissionException
     */
    private void checkGroupOwner(EIMGroup group, String error) throws EIMPermissionException {
        String owner = group.getOwner();
        if ((owner == null) || (!(currentAccount.equals(owner)))) {
            throw new EIMPermissionException(error);
        }
    }
    
    /**
     * 登陆后加载群组消息
     */
    public void joinGroupsAfterLogin() {
        try {
            new Thread() {
                
                public void run() {
                    List<EIMGroup> lstGroups = getAllGroups();
                    for (EIMGroup group : lstGroups) {
                        String groupJID = EIMAccountUtils.getJIDFromAccount(group.getGroupId());
                        // 加载所有的群组聊天对象
                        getMUC(groupJID);
                    }
                }
            }.start();
        } catch (Exception e) {
            EIMLog.e(_TAG, "登陆后加载群组消息失败：" + e.getMessage());
        }
        
    }
    
    /**
     * 根据群组账号获取聊天室对象
     * 
     * @param JID
     * @return
     */
    public synchronized MultiUserChat getMUC(String JID) {
        try {
            if (!JID.contains("@")) {
                JID += EIMConfig.MUC_DOMAIN_SUFFIX;
            }
            MultiUserChat multiUserChat = this.allMultiUserChats.get(JID);
            if (multiUserChat == null) {
                multiUserChat = new MultiUserChat(xmppConnectionManager.getConnection(), JID);
                this.addMUC(JID, multiUserChat);
            }
            if (!multiUserChat.isJoined()) {
                // 将当前用户加入到群组聊天中
                multiUserChat.join(currentAccount);
            }
            return multiUserChat;
        } catch (Exception e) {
            EIMLog.e(_TAG, "获取聊天室对象失败：" + e.getMessage());
        }
        return null;
    }
    
    /**
     * 将群组聊天室对象加入缓存中
     * 
     * @param JID
     * @param multiUserChat
     */
    private void addMUC(String JID, MultiUserChat multiUserChat) {
        this.allMultiUserChats.put(JID, multiUserChat);
        // 设置群组操作监听器
        multiUserChat.addUserStatusListener(new EIMMemberStatusListener(JID));
    }
    
    private EIMGroup getMUC(String groupJID, String account, boolean flag, boolean isJoin) {
        String groupAccount = EIMAccountUtils.getGroupIdFromGroupJID(groupJID);
        EIMGroup group = new EIMGroup(groupAccount);
        try {
            // 从服务器端获取群组聊天室信息
            RoomInfo roomInfo = MultiUserChat.getRoomInfo(this.xmppConnectionManager.getConnection(), groupJID);
            if (roomInfo == null) {
                return null;
            }
            
            group.setGroupName(roomInfo.getRoom());
            group.setDescription(roomInfo.getDescription());
            group.setMembersOnly(roomInfo.isMembersOnly());
            
            MultiUserChat multiUserChat = this.getMUCWithoutJoin(groupJID);
            if (isJoin) {
                // 聊天室中加入当前登录账号
                multiUserChat.join(account);
            }
            
            if (!flag) {
                return group;
            }
            
            // 获取群组的拥有者
            Collection<Affiliate> colAffiliate = multiUserChat.getOwners();
            for (Affiliate affiliate : colAffiliate) {
                String jid = affiliate.getJid();
                String owner = EIMAccountUtils.getAccountFromJID(jid);
                group.setOwner(owner);
            }
            
            group.addMember(group.getOwner());
            
            // 获取群组成员
            Collection<Affiliate> colMembers = multiUserChat.getMembers();
            for (Affiliate affiliate : colMembers) {
                String jid = affiliate.getJid();
                String member = EIMAccountUtils.getAccountFromJID(jid);
                group.addMember(member);
            }
            
            if (group.isPublic() && !group.isAllowInvites()) {
                Collection<Occupant> colParticipants = multiUserChat.getParticipants();
                for (Occupant occupant : colParticipants) {
                    String jid = occupant.getJid();
                    String member = EIMAccountUtils.getAccountFromJID(jid);
                    if (!group.members.contains(member)) {
                        group.addMember(member);
                    }
                }
            }
        } catch (Exception e) {
            EIMLog.e(_TAG, "获取聊天室信息失败:" + e.getMessage());
        }
        return group;
    }
    
    private MultiUserChat getMUCWithoutJoin(String JID) {
        if (!JID.contains("@")) {
            JID += EIMConfig.MUC_DOMAIN_SUFFIX;
        }
        MultiUserChat multiUserChat = this.allMultiUserChats.get(JID);
        if (multiUserChat == null) {
            multiUserChat = new MultiUserChat(this.xmppConnectionManager.getConnection(), JID);
            this.addMUC(JID, multiUserChat);
        }
        return multiUserChat;
    }
    
    public void removeMucs() {
        this.allMultiUserChats.clear();
    }
    
    /**
     * 从数据库中加载所有群组信息
     */
    public void loadAllGroups() {
        this.allGroups = EIMGroupTable.getInstance().queryAllGroup();
    }
    
    /**
     * 获取所有群组消息
     * 
     * @return
     */
    public List<EIMGroup> getAllGroups() {
        return Collections.unmodifiableList(new ArrayList<EIMGroup>(this.allGroups.values()));
    }
    
    public void logout() {
        try {
            this.allGroups.clear();
            this.allGroupChangeListeners.clear();
            this.allMultiUserChats.clear();
            this.allGroupChangeEvents.clear();
            MultiUserChat.removeInvitationListener(this.xmppConnectionManager.getConnection(), this.invitationListener);
        } catch (Exception e) {
            // TODO: handle exception
        }
        
    }
    
    /**
     * 处理群组离线消息
     */
    public void processOfflineMessages() {
        
    }
    
    /**
     * 添加群组操作监听器
     * 
     * @param groupChangeListener
     */
    public void addGroupChangeListener(EIMGroupChangeListener groupChangeListener) {
        if (!this.allGroupChangeListeners.contains(groupChangeListener)) {
            this.allGroupChangeListeners.add(groupChangeListener);
        }
    }
    
    /**
     * 删除群组操作监听器s
     * 
     * @param groupChangeListener
     */
    public void removeGroupChangeListener(EIMGroupChangeListener groupChangeListener) {
        this.allGroupChangeListeners.remove(groupChangeListener);
    }
    
    public void addGroupChangeEvent(EIMGroupChangeEvent groupChangeEvent) {
        if (!this.allGroupChangeEvents.contains(groupChangeEvent)) {
            this.allGroupChangeEvents.add(groupChangeEvent);
        }
    }
    
    /**
     * 生成群组ID
     * 
     * @return
     */
    private String generateGroupId() {
        return UUID.randomUUID().toString();
    }
    
    public EIMGroup getGroup(String groupId) {
        return this.allGroups.get(groupId);
    }
    
    /**
     * 删除客戶端的群组信息
     */
    public void deleteGroupClient(String groupId) {
        try {
            // 从数据库中刷出该群组
            EIMGroupTable.getInstance().deleteGroup(groupId);
            this.allGroups.remove(groupId);
            // 删除群组聊天会话
            EIMChatManager.getInstance().deleteConversation(groupId);
        } catch (Exception e) {
            EIMLog.e(_TAG, "删除群组失败:" + e.getMessage());
        }
    }
    
    public void setAutoAcceptInvitation(boolean autoAcceptInvitation) {
        this.autoAcceptInvitation = autoAcceptInvitation;
    }
}
